package mysql;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author 化尘成影
 * @Description 数据库连接工具
 * @date 2022/6/9 10:42
 */
public class JDBCUtil {
    private static String driverClassName;
    private static String url;
    private static String username;
    private static String password;
    private static DruidDataSource druidDataSource = new DruidDataSource();
    private static Connection connection;
    private static PreparedStatement preparedStatement;

    //连接数据库
    static {
        InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driverClassName = properties.getProperty("driverClassName");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
    }

    protected Connection getConnection() {
        try {
            connection = druidDataSource.getConnection();
        } catch (SQLException sqlException) {
            System.out.println("数据库连接失败");
        }
        return connection;
    }

    protected PreparedStatement getStatement(String sql){
        try{
            preparedStatement = getConnection().prepareStatement(sql);
        } catch (SQLException sqlException){
            System.out.println("获取失败");
        }
        return preparedStatement;
    }

    protected void closeAll(){
        try {
            if(connection != null){
                connection.close();
            }
            if(preparedStatement != null){
                preparedStatement.close();
            }
        } catch (SQLException sqlException){
            sqlException.printStackTrace();
        }
    }
}
